package com.liuwei.netty.coder;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    // 客户端发送完数据就会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //ByteBuf buf = (ByteBuf) msg;
        // log.info("客户端发送的数据:" + msg);

        log.info("客户端发送的数据:" + (Student)msg);

    }

    // 读完数据发送数据给客户端
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //ByteBuf buf = Unpooled.copiedBuffer("hello client".getBytes(StandardCharsets.UTF_8));
        // 将数据写入通道
        ctx.writeAndFlush("服务端发送的测试数据");
    }

    // 异常捕获
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error(cause.getMessage());
        // 关闭通道
        ctx.close();
    }
}
